﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using personalplaner.business.dienstplan;
using personalplaner.business.dienstplan.plancollection;
using System;
using personalplaner.business.extensions;

namespace personalplaner.common.controls
{
	[TemplatePart(Name= "PART_DiensteGrid", Type=typeof(DataGrid))]
	[TemplatePart(Name= "PART_DiensteOverviewGrid", Type=typeof(DataGrid))]
	[TemplatePart(Name = "PART_PersonenGrid", Type = typeof(DataGrid))]
    [TemplatePart(Name = "PART_DienstOverviewHeaderGrid", Type = typeof(DataGrid))]
	[TemplatePart(Name = "PART_SaldoGrid", Type = typeof(DataGrid))]
	public class PlanGrid : Control
    {
        #region Construction

        static PlanGrid()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(PlanGrid), new FrameworkPropertyMetadata(typeof(PlanGrid)));
		}

		public PlanGrid()
		{
		}

        #endregion

        #region Implamentation

        //public void RefreshLayout()
        //{
        //    //SaldoGrid.InvalidateMeasure();
        //    //PersonenGrid.InvalidateMeasure();
        //    //DienstOverviewHeaderGrid.InvalidateMeasure();

        //    PersonenGrid.Width = 0;
        //    PersonenGrid.Width = Double.NaN;

        //    var grid = PersonenGrid as DataGrid;
        //    if (grid != null)
        //    {
        //        //grid.Columns[0].de
        //        grid.Columns[0].Width = DataGridLength.SizeToCells;

        //        PersonenGrid.Width = grid.Columns[0].ActualWidth + 3;
        //    }


        //    PersonenGrid.UpdateLayout();
        //    //this.InvalidateMeasure();
        //}

        //protected override Size MeasureOverride(Size constraint)
        //{
        //    return base.MeasureOverride(constraint);

        //    //int count = this.VisualChildrenCount;

        //    //if (count > 0)
        //    //{
        //    //    UIElement child = (UIElement)(this.GetVisualChild(0));
        //    //    if (child != null)
        //    //    {
        //    //        //Helper.SetMeasureDataOnChild(this, child, constraint);  // pass along MeasureData so it continues down the tree.
        //    //        child.Measure(constraint);
        //    //        return child.DesiredSize;
        //    //    }
        //    //}

        //    //return new Size(0.0, 0.0);
        //}
        
		public override void OnApplyTemplate()
		{
			

			base.OnApplyTemplate();

			SaldoGrid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            PersonenGrid = GetTemplateChild("PART_PersonenGrid") as FrameworkElement; // DataGrid;
            DienstOverviewHeaderGrid = GetTemplateChild("PART_DienstOverviewHeaderGrid") as ListView;

            InitializeDienstGrid();
            InitializePersonGrid();
            InitializePlanDienstGrid();

            OnShowDiffColumnChanged(false);
            OnShowHabenColumnChanged(false);
            OnShowSollColumnChanged(false);
            OnShowAnpassungColumnChanged(false);
            OnShowVortragColumnChanged(true);
		}

		void _saldoGrid_Loaded(object sender, RoutedEventArgs e)
		{
			var grid = sender as DataGrid;

			if (grid != null)
				RefreshGridColumns(grid);
		}

        private static void RefreshGridColumns(DataGrid grid)
        {
            double width = 0.0;
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                grid.Columns[i].Width = 0;
                grid.UpdateLayout();
                if (grid.Columns[i].Visibility != Visibility.Visible)
                    continue;

                grid.Columns[i].Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
                width += grid.Columns[i].ActualWidth + 0.5;
            }

            grid.UpdateLayout();
            grid.Width = width + 0.5;
        }

        #endregion

        #region Grids

        #region Personen grid

        FrameworkElement _personenGrid;
        protected FrameworkElement PersonenGrid
        {
            get
            {
                return _personenGrid;
            }
            set
            {
                if (_personenGrid != null)
                {
                    _personenGrid.SizeChanged -= new SizeChangedEventHandler(personenGridSizeChanged);
                    _personenGrid.TargetUpdated -= new EventHandler<System.Windows.Data.DataTransferEventArgs>(personenGridTargetUpdated);
                }

                _personenGrid = value;

                if (_personenGrid != null)
                {
                    _personenGrid.SizeChanged += new SizeChangedEventHandler(personenGridSizeChanged);
                    _personenGrid.TargetUpdated += new EventHandler<System.Windows.Data.DataTransferEventArgs>(personenGridTargetUpdated);
                }
            }
        }

        void personenGridTargetUpdated(object sender, System.Windows.Data.DataTransferEventArgs e)
        {
            var grid = PersonenGrid as DataGrid;
            if (grid != null)
            {
                //grid.Width = 0;
                ////grid.Columns[0].de
                //grid.Columns[0].Width = 0;
                //grid.UpdateLayout();
                //grid.Columns[0].Width = DataGridLength.SizeToCells;
                ////grid.Columns[0].Width = new DataGridLength(1, DataGridLengthUnitType.Star);

                //grid.Width = double.NaN;
                //grid.Width = grid.Columns[0].ActualWidth + (grid.Columns[1].Visibility == Visibility.Visible ? grid.Columns[1].ActualWidth : 0) + 2;
                //grid.UpdateLayout();

                RefreshGridColumns(grid);

                //if (grid.Columns[1].Visibility == Visibility.Visible)
                //{
                //    var child = this.GetVisualChild(0) as FrameworkElement;
                //    if (child != null)
                //    {
                //        if (child.ActualWidth < this.ActualWidth)
                //        {
                //            grid.Columns[1].Header = "Pns";
                //            RefreshGridColumns(grid);
                //        }
                //    }
                //}
            }
            this.UpdateLayout();
        }

        void personenGridSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (DienstOverviewHeaderGrid == null)
                return;

            // make sure that the dienste sumary grid has the same size
            DienstOverviewHeaderGrid.Width = PersonenGrid.ActualWidth;
            var grid = DienstOverviewHeaderGrid.View as GridView;
            if (grid != null)
            {
                if ((PersonenGrid.ActualWidth - grid.Columns[1].ActualWidth > 1))
                    grid.Columns[0].Width = (PersonenGrid.ActualWidth - grid.Columns[1].ActualWidth) - 1;// -11;
            }
        }

        #endregion

        #region DienstOverviewHeaderGrid

        ListView _dienstOverviewHeaderGrid;
        protected ListView DienstOverviewHeaderGrid
        {
            get
            {
                return _dienstOverviewHeaderGrid;
            }
            set
            {
                _dienstOverviewHeaderGrid = value;
            }
        }

        #endregion

        #region SaldoGrid

        DataGrid _saldoGrid;
        protected DataGrid SaldoGrid
        {
            get
            {
                return _saldoGrid;
            }
            set
            {
                if (_saldoGrid != null)
                    _saldoGrid.Loaded -= _saldoGrid_Loaded;

                _saldoGrid = value;

                if (_saldoGrid != null)
                    _saldoGrid.Loaded += _saldoGrid_Loaded;
            }
        }

        #endregion

        #endregion

        #region DependencyProperties

        #region RowHeight

        /// <summary>
		///     The default height of a row.
		/// </summary>
		public double RowHeight
		{
			get { return (double)GetValue(RowHeightProperty); }
			set { SetValue(RowHeightProperty, value); }
		}

		/// <summary>
		///     The DependencyProperty for RowHeight.
		/// </summary>
		public static readonly DependencyProperty RowHeightProperty =
			DependencyProperty.Register("RowHeight", typeof(double), typeof(PlanGrid), new FrameworkPropertyMetadata(19.0));//, new PropertyChangedCallback(OnNotifyCellsPresenterPropertyChanged)));

		///// <summary>
		/////     Notifies each CellsPresenter about property changes.
		///// </summary>
		//private static void OnNotifyCellsPresenterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		//{
		//    ((DataGrid)d).NotifyPropertyChanged(d, e, DataGridNotificationTarget.CellsPresenter);
        //} 

        #endregion

        #region Command

        /// <summary>
		/// Get or set the Command property 
		/// </summary>
		[Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public ICommand Command
		{
			get
			{
				return (ICommand)GetValue(CommandProperty);
			}
			set
			{
				SetValue(CommandProperty, value);
			}
		}

		public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(PlanGrid), new FrameworkPropertyMetadata(null));

        #endregion

        #region ShowPensumColumn

        [Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowPensumColumn
		{
			get
			{
				return (bool)GetValue(ShowPensumColumnProperty);
			}
			set
			{
				SetValue(ShowPensumColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowPensumColumnProperty = DependencyProperty.Register("ShowPensumColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowPensumColumnChanged));

		private static void OnShowPensumColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
		    var newValue = (bool)e.NewValue;

			ic.OnShowPensumColumnChanged(newValue);
		}

		/// <summary> 
		/// Called when the value of ShowPensumColumn changes. 
		/// </summary>
		protected virtual void OnShowPensumColumnChanged(bool value)
		{
			InitializePersonGrid();
		}

        #endregion

        #region Show Vortrag

        [Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowVortragColumn
		{
			get
			{
				return (bool)GetValue(ShowVortragColumnProperty);
			}
			set
			{
				SetValue(ShowVortragColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowVortragColumnProperty = DependencyProperty.Register("ShowVortragColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowVortragColumnChanged));

		private static void OnShowVortragColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			//var newValue = (bool)e.NewValue;

			ic.OnShowVortragColumnChanged(true);
		}

		/// <summary> 
		/// Called when the value of ShowDiffColumn changes. 
		/// </summary>
		protected virtual void OnShowVortragColumnChanged(bool value)
		{
            //var grid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            var grid = SaldoGrid;
			if (grid == null)
				return;

			grid.Columns[0].Visibility = ShowDiffColumn ? Visibility.Visible : Visibility.Collapsed;

			if (value)
				RefreshGridColumns(grid);
		}

		#endregion

		#region Show Soll

		[Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowSollColumn
		{
			get
			{
				return (bool)GetValue(ShowSollColumnProperty);
			}
			set
			{
				SetValue(ShowSollColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowSollColumnProperty = DependencyProperty.Register("ShowSollColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowSollColumnChanged));

		private static void OnShowSollColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			//var newValue = (bool)e.NewValue;

			ic.OnShowSollColumnChanged(true);
		}

		/// <summary> 
		/// Called when the value of ShowSollColumn changes. 
		/// </summary>
		protected virtual void OnShowSollColumnChanged(bool value)
		{
            //var grid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            var grid = SaldoGrid;
            if (grid == null)
                return;

            grid.Columns[1].Visibility = ShowSollColumn ? Visibility.Visible : Visibility.Collapsed;

            if (value)
            {
                RefreshGridColumns(grid);
                UpdateLayout();
            }
		}

		#endregion

		#region Show Haben

		[Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowHabenColumn
		{
			get
			{
				return (bool)GetValue(ShowHabenColumnProperty);
			}
			set
			{
				SetValue(ShowHabenColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowHabenColumnProperty = DependencyProperty.Register("ShowHabenColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowHabenColumnChanged));

		private static void OnShowHabenColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			//var newValue = (bool)e.NewValue;

			ic.OnShowHabenColumnChanged(true);
		}

		/// <summary> 
		/// Called when the value of ShowHabenColumn changes. 
		/// </summary>
		protected virtual void OnShowHabenColumnChanged(bool value)
		{
            //var grid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            var grid = SaldoGrid;
            if (grid == null)
                return;

            grid.Columns[2].Visibility = ShowHabenColumn ? Visibility.Visible : Visibility.Collapsed;

            if (value)
            {
                RefreshGridColumns(grid);
                UpdateLayout();
            }

		}

		#endregion

		#region Show Anpassung

		[Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowAnpassungColumn
		{
			get
			{
				return (bool)GetValue(ShowAnpassungColumnProperty);
			}
			set
			{
				SetValue(ShowAnpassungColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowAnpassungColumnProperty = DependencyProperty.Register("ShowAnpassungColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowAnpassungColumnChanged));

		private static void OnShowAnpassungColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			//var newValue = (bool)e.NewValue;

			ic.OnShowAnpassungColumnChanged(true);
		}

		/// <summary> 
		/// Called when the value of ShowDiffColumn changes. 
		/// </summary>
		protected virtual void OnShowAnpassungColumnChanged(bool value)
		{
            //var grid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            var grid = SaldoGrid;
			if (grid == null)
				return;

			grid.Columns[3].Visibility = ShowDiffColumn ? Visibility.Visible : Visibility.Collapsed;

			if (value)
				RefreshGridColumns(grid);
		}

		#endregion

		#region Show Diff

		[Bindable(true), Category("Action")]
		[Localizability(LocalizationCategory.NeverLocalize)]
		public bool ShowDiffColumn
		{
			get
			{
				return (bool)GetValue(ShowDiffColumnProperty);
			}
			set
			{
				SetValue(ShowDiffColumnProperty, value);
			}
		}
		public static readonly DependencyProperty ShowDiffColumnProperty = DependencyProperty.Register("ShowDiffColumn", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(true, OnShowDiffColumnChanged));

		private static void OnShowDiffColumnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			//var newValue = (bool)e.NewValue;

			ic.OnShowDiffColumnChanged(true);
		}

		/// <summary> 
		/// Called when the value of ShowDiffColumn changes. 
		/// </summary>
		protected virtual void OnShowDiffColumnChanged(bool value)
		{
            //var grid = GetTemplateChild("PART_SaldoGrid") as DataGrid;
            var grid = SaldoGrid;
            if (grid == null)
                return;

            grid.Columns[4].Visibility = ShowDiffColumn ? Visibility.Visible : Visibility.Collapsed;

            if (value)
            {
                RefreshGridColumns(grid);
                UpdateLayout();
            }
		}

		#endregion

        #region Collection

        public IList<IDienstPlanRow> Collection
		{
			get
			{
				return (IList<IDienstPlanRow>)GetValue(CollectionProperty);
			}
			set
			{
				SetValue(CollectionProperty, value);
			}
		}

		public static readonly DependencyProperty CollectionProperty = 
			DependencyProperty.Register("Collection", typeof(IList<IDienstPlanRow>), typeof(PlanGrid),
										  new FrameworkPropertyMetadata((IList<IDienstPlanRow>)null, new PropertyChangedCallback(OnItemsSourceChanged)));

		private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			var oldValue = (IList<IDienstPlanRow>)e.OldValue;
		    var newValue = (IList<IDienstPlanRow>)e.NewValue;

			ic.OnItemsSourceChanged(oldValue, newValue);
		}

		/// <summary> 
		/// Called when the value of ItemsSource changes. 
		/// </summary>
		protected virtual void OnItemsSourceChanged(IList<IDienstPlanRow> oldValue, IList<IDienstPlanRow> newValue)
		{
			InitializeDienstGrid();
		}

        #endregion

        #region PlanDienstOverview

        public IList<DienstOverviewRow> PlanDienstOverview
		{
			get
			{
				return (IList<DienstOverviewRow>)GetValue(PlanDienstOverviewProperty);
			}
			set
			{
				SetValue(PlanDienstOverviewProperty, value);
			}
		}

		public static readonly DependencyProperty PlanDienstOverviewProperty =
			DependencyProperty.Register("PlanDienstOverview", typeof(IList<DienstOverviewRow>), typeof(PlanGrid),
										  new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnPlanDienstOverviewChanged)));

		private static void OnPlanDienstOverviewChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var ic = (PlanGrid)d;
			var newValue = (IList<DienstOverviewRow>)e.NewValue;

			ic.OnPlanDienstOverviewChanged(newValue);
		}

		/// <summary> 
		/// Called when the value of ItemsSource changes. 
		/// </summary>
		protected virtual void OnPlanDienstOverviewChanged(IList<DienstOverviewRow> value)
		{
			InitializePlanDienstGrid();
		}

        #endregion

        #region IsReadOnly

        public bool IsReadOnly
        {
            get { return (bool)GetValue(IsReadOnlyProperty); }
            set { SetValue(IsReadOnlyProperty, value); }
        }

        public static readonly DependencyProperty IsReadOnlyProperty =
            DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(PlanGrid), new UIPropertyMetadata(false));

        #endregion

        #region IsGridForPrinting

        public bool IsGridForPrinting
        {
            get { return (bool)GetValue(IsGridForPrintingProperty); }
            set { SetValue(IsGridForPrintingProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsGridForPrinting.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsGridForPrintingProperty =
            DependencyProperty.Register("IsGridForPrinting", typeof(bool), typeof(PlanGrid), new FrameworkPropertyMetadata(false, OnIsGridForPrintingPropertyChanged));

        private static void OnIsGridForPrintingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ic = (PlanGrid)d;
            //var newValue = (bool)e.NewValue;

            ic.OnIsGridForPrintingChanged((bool)e.NewValue);
        }

        /// <summary> 
        /// Called when the value of ShowDiffColumn changes. 
        /// </summary>
        protected virtual void OnIsGridForPrintingChanged(bool value)
        {
            if (value)
            {
                var grid = PersonenGrid as DataGrid;
                if (grid != null)
                {
                    //if (grid.Columns[1].Visibility == Visibility.Visible)
                    //{
                        var child = this.GetVisualChild(0) as FrameworkElement;
                        if (child != null)
                        {
                            if (child.ActualWidth < this.ActualWidth)
                            {
                                grid.Columns[1].Header = "Pns";
                                RefreshGridColumns(grid);
                            }
                        }
                    //}
                }
                this.UpdateLayout();
            }
        }

        #endregion

        #endregion

        #region Initialization

        private void InitializeDienstGrid()
		{
            var stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            if (DiensteGrid == null)
                return;

			if (Collection == null)
				return;

            var planItems = new ObservableCollection<IList<PlanItem>>();
			foreach (var pi in Collection)
				planItems.Add(new ObservableCollection<PlanItem>(pi));



            //Items = planItems;



            //return;

            //DiensteGrid.Columns.Clear();

            //DataTemplate celltemplate = null;
            //try
            //{
            //    celltemplate = (DataTemplate)FindResource("PART_CellTemplate");
            //}
            //catch (System.Windows.ResourceReferenceKeyNotFoundException) { }

            //int index = 0;
            //foreach (var column in planItems[0])
            //{
            //    var col = new DataGridPlanItemTemplateColumn
            //    {
            //        IsReadOnly = true,
            //        CanUserReorder = false,

            //        Header = column.Datum.Day,

            //        ColumnName = string.Format("[{0}]", index),
            //        CellTemplate = celltemplate
            //    };

            //    //var col = new DataGridPlanItemColumn();

            //    //var col = new DataGridTextColumn();

            //    index++;
            //    DiensteGrid.Columns.Add(col);
            //}

            DiensteGrid.ItemsSource = planItems;

            System.Diagnostics.Trace.WriteLine(string.Format("Initializing the DiensteGrid took {0} Milliseconds",stopWatch.ElapsedMilliseconds.ToString("0,0")));
		}
        
		private void InitializePersonGrid()
		{
            //var grid = GetTemplateChild("PART_PersonenGrid") as DataGrid;
            var dataGrid = PersonenGrid as DataGrid;
            if (dataGrid != null)
            {
                dataGrid.Columns[1].Visibility = ShowPensumColumn ? Visibility.Visible : Visibility.Collapsed;
                dataGrid.Columns[1].Width = 0;



                if (IsGridForPrinting)
                {
                    dataGrid.Columns[1].Header = "Pns";
                    RefreshGridColumns(dataGrid);
                    this.UpdateLayout();
                }

                return;
            }

            var listView = PersonenGrid as ListView;
            if (listView != null)
            {
                var gridView = listView.View as GridView;
                if (gridView != null)
                {
                    gridView.Columns[1].Width = ShowPensumColumn ? double.NaN : 0;
                }
                return;
            }
		}

		private void InitializePlanDienstGrid()
		{
			var grid = GetTemplateChild("PART_DiensteOverviewGrid") as DataGrid;
			if (grid == null)
				return;

            if (PlanDienstOverview == null || PlanDienstOverview.Count == 0)
            {
                grid.Visibility = System.Windows.Visibility.Collapsed;

                //var headergrid = GetTemplateChild("PART_DienstOverviewHeaderGrid") as DataGrid;
                var headergrid = DienstOverviewHeaderGrid;
                if (headergrid != null)
                    headergrid.Visibility = System.Windows.Visibility.Collapsed;

                return;
            }

			var dienstItems = new ObservableCollection<IList<DienstOverviewItem>>();
			foreach (var pi in PlanDienstOverview)
				dienstItems.Add(new ObservableCollection<DienstOverviewItem>(pi));

			grid.Columns.Clear();
            
            DataTemplate celltemplate = null;
            try
            {
                celltemplate = (DataTemplate)FindResource("PART_DienstOverviewCellTemplate");
            }
            catch (System.Windows.ResourceReferenceKeyNotFoundException) { }

			int index = 0;
			foreach (var column in dienstItems[0])
			{
				var col = new DataGridPlanItemTemplateColumn
				{
					IsReadOnly = true,
					CanUserReorder = false,

					Header = column.Datum.Day,

					ColumnName = string.Format("[{0}]", index),
					CellTemplate = celltemplate
				};

				index++;
				grid.Columns.Add(col);
			}

			grid.ItemsSource = dienstItems;
		}

		#endregion

        #region Control Properties

        DiensteDataGrid _diensteGrid;
        private DiensteDataGrid DiensteGrid
        {
            get
            {
                if (_diensteGrid == null)
                {
                    _diensteGrid = GetTemplateChild("PART_DiensteGrid") as DiensteDataGrid;
                    if (_diensteGrid != null)
                    {
                        _diensteGridLoadingStopWatch = new System.Diagnostics.Stopwatch();
                        _diensteGridLoadingStopWatch.Start();
                        _diensteGrid.Loaded += new RoutedEventHandler(DiensteGrid_Loaded);
                    }
                }
                return _diensteGrid;
            }
        }

        System.Diagnostics.Stopwatch _diensteGridLoadingStopWatch;
        void DiensteGrid_Loaded(object sender, RoutedEventArgs e)
        {
            if (_diensteGridLoadingStopWatch == null)
                return;

            System.Diagnostics.Trace.WriteLine(string.Format("Loading the DiensteGrid took {0} Milliseconds", _diensteGridLoadingStopWatch.ElapsedMilliseconds.ToString("0,0")));
        }

        #endregion
    }
}
